package com.earthea.scaffold.system.controller;

import com.earthea.scaffold.common.aop.annotation.ControllerLog;
import com.earthea.scaffold.common.entity.BaseDataRsp;
import com.earthea.scaffold.common.entity.BaseRsp;
import com.earthea.scaffold.common.enums.OperateTypeEnum;
import com.earthea.scaffold.common.enums.HttpCodeEnum;
import com.earthea.scaffold.common.util.SecurityUtils;
import com.earthea.scaffold.domain.LoginUser;
import com.earthea.scaffold.domain.SysFile;
import com.earthea.scaffold.domain.User;
import com.earthea.scaffold.system.entity.request.UpdatePwdReq;
import com.earthea.scaffold.system.entity.request.UpdateUserReq;
import com.earthea.scaffold.system.service.TokenService;
import com.earthea.scaffold.system.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * 个人信息 业务处理
 */
@RestController
@RequestMapping("/api/system/profile")
public class ProfileController {
    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 修改用户
     */
    @PutMapping
    @ControllerLog(title = "个人信息修改", operateType = OperateTypeEnum.UPDATE)
    public BaseRsp updateProfile(@Validated @RequestBody UpdateUserReq updateUserReq) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.equals(loginUser.getUsername(), updateUserReq.getUsername()) && StringUtils.equals(loginUser.getEmail(), updateUserReq.getEmail()) && StringUtils.equals(loginUser.getPhone(), updateUserReq.getPhone()) && Objects.equals(loginUser.getSex(), updateUserReq.getSex())) {
            return BaseRsp.failed("个人信息没有发生变化");
        } else if (!StringUtils.equals(loginUser.getUsername(), updateUserReq.getUsername()) && userService.existUserNameUnique(updateUserReq.getUsername())) {
            return BaseRsp.failed("修改用户'" + updateUserReq.getUsername() + "'失败，用户名已存在");
        } else if (!StringUtils.equals(loginUser.getPhone(), updateUserReq.getPhone()) && userService.existPhoneUnique(updateUserReq.getPhone())) {
            return BaseRsp.failed("修改用户'" + updateUserReq.getPhone() + "'失败，手机号已存在");
        } else if (!StringUtils.equals(loginUser.getEmail(), updateUserReq.getEmail()) && userService.existEmailUnique(updateUserReq.getEmail())) {
            return BaseRsp.failed("修改用户'" + updateUserReq.getEmail() + "'失败，邮箱账号已存在");
        }

        User user = new User();
        user.setUserId(loginUser.getUserId());
        user.setUsername(updateUserReq.getUsername());
        user.setPhone(updateUserReq.getPhone());
        user.setEmail(updateUserReq.getEmail());
        user.setSex(updateUserReq.getSex());
        user.setUpdateBy(loginUser.getUserId());
        if (userService.modifyById(user).isSuccess()) {
            // 更新缓存用户信息
            loginUser.setUsername(updateUserReq.getUsername());
            loginUser.setPhone(updateUserReq.getPhone());
            loginUser.setEmail(updateUserReq.getEmail());
            loginUser.setSex(updateUserReq.getSex());
            tokenService.setLoginUser(loginUser);
            return BaseRsp.success();
        }
        return BaseRsp.failed("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    @ControllerLog(title = "个人信息重置密码", operateType = OperateTypeEnum.UPDATE, isSaveRequestData = false)
    public BaseRsp updatePwd(@Validated @RequestBody UpdatePwdReq req) {
        String oldPassword = req.getOldPassword();
        String newPassword = req.getNewPassword();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String password = loginUser.getPassword();
        if (!encoder.matches(oldPassword, password)) {
            return BaseRsp.failed("修改密码失败，旧密码错误");
        }
        if (encoder.matches(newPassword, password)) {
            return BaseRsp.failed("新密码不能与旧密码相同");
        }
        newPassword = encoder.encode(newPassword);
        User user = new User();
        user.setUserId(loginUser.getUserId());
        user.setPassword(newPassword);
        if (userService.modifyById(user).isSuccess()) {
            // 更新缓存用户密码
            loginUser.setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return BaseRsp.success();
        }
        return BaseRsp.failed("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @ControllerLog(title = "个人信息修改头像", operateType = OperateTypeEnum.UPDATE)
    @PostMapping("/avatar")
    public BaseDataRsp<String> avatar(@RequestParam("file") MultipartFile file) {
        BaseDataRsp<String> rsp = new BaseDataRsp<>();
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            BaseDataRsp<SysFile> baseRsp = userService.updateAvatar(SecurityUtils.getLoginUserId(), file);
            if (baseRsp.isSuccess()) {
                rsp.setData(baseRsp.getData().getFilePath());
                // 更新缓存用户头像
                loginUser.setAvatar(baseRsp.getData().getFilePath());
                tokenService.setLoginUser(loginUser);
                return rsp;
            }
        }
        rsp.setCode(HttpCodeEnum.FAIL.getCode());
        rsp.setMsg("上传图片异常，请联系管理员");
        return rsp;
    }
}
